# -------------------------------------------------------------------
#       -*- coding: utf-8 -*-
#   @Project    :   py37_studentSystem
#   @File       :   util.py
#   @Author     :   WANGYU
#   @Time       :   2021-08-04 16:51:39
#   @Software   :   PyCharm
#   @Desc       :   
# -------------------------------------------------------------------
import os

filename = 'student.txt'


def insert():
    print('添加信息')
    student_list = []
    while True:
        id = input('请输入ID（如1001）：')
        if not id:
            break
        name = input('请输入姓名：')
        if not name:
            break
        try:
            englist = int(input('请输入英语成绩：'))
            python = int(input('请输入python成绩：'))
            java = int(input('请输入java成绩：'))
        except:
            print('输入无效，请输入整数')
            continue
        # 将录入的信息保存在字典中
        student = {'id': id, 'name': name, 'english': englist, 'python': python, 'java': java}
        # 将信息添加到列表中
        student_list.append(student)
        answer = input('是否继续添加？y/n\n')
        if answer == 'y':
            continue
        else:
            break
    # 调用save（）函数
    save(student_list)
    print("信息录入完毕！")


def save(lst):
    try:
        stu_txt = open(filename, 'a', encoding='utf-8')
    except:
        stu_txt = open(filename, 'w', encoding='utf-8')
    for item in lst:
        stu_txt.write(str(item) + '\n')
    stu_txt.close()


def delete():
    while True:
        student_id = input('请输入ID：')
        if student_id != '':
            if os.path.exists(filename):
                with open(filename, 'r', encoding='utf-8') as file:
                    student_old = file.readlines()
            else:
                student_old = []
            flag = False  # 标记是否删除
            if student_old:
                with open(filename, 'w', encoding='utf-8') as wfile:
                    d = {}
                    for item in student_old:
                        # print(item)
                        d = dict(eval(item))  # 将字符串转成字典
                        # print(d)
                        if d['id'] != student_id:
                            wfile.write(str(d) + '\n')
                        else:
                            flag = True
                    if flag:
                        print(f'id 为{student_id}的学生信息已被删除')
                    else:
                        print(f'没有找到ID为{student_id}的信息')
            else:
                print('无信息')
                break
            show()  # 删除后重新显示学生信息
            answer = input('是否继续删除？y/n\n')
            if answer == 'y':
                continue
            else:
                break


def modify():
    show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_old = rfile.readlines()
    else:
        return
    student_id = input('请输入要修改的ID：')
    with open(filename, 'w', encoding='utf-8') as wfile:
        for item in student_old:
            d = dict(eval(item))
            if d['id'] == student_id:
                print('find info, you can update data!')
                while True:
                    try:
                        d['name'] = input('input student name:')
                        d['english'] = input('input english score:')
                        d['python'] = input('input python score:')
                        d['java'] = input('input java score:')
                    except:
                        print('wrong input ,please input again!')
                    else:
                        break  # 退出循环
                wfile.write(str(d) + '\n')  # 将修改的信息写入文件
                print('update success!')
            else:
                wfile.write(str(d) + '\n')  # 将未修改信息写入文件
        answer = input('是否继续修改其他信息？(y/n)\n')
        if answer == 'y':
            modify()


def search():
    student_query = []
    while True:
        id = ''
        name = ''
        if os.path.exists(filename):
            mode = input('按ID查找输入1，按姓名查找输入2：')
            if mode == '1':
                id = input('请输入ID：')
            elif mode == '2':
                name = input('请输入姓名：')
            else:
                print('输入有误，重新输入！')
                search()
            with open(filename, 'r', encoding='utf-8') as rfile:
                student = rfile.readlines()
                for item in student:
                    d = dict(eval(item))
                    if id != '':
                        if d['id'] == id:
                            student_query.append(d)

                    elif name != '':
                        if d['name'] == name:
                            student_query.append(d)
            # 显示查询结果
            show_student(student_query)
            # 清空列表
            student_query.clear()
            answer = input('是否继续查询？(y/n)\n')
            if answer == 'y':
                continue
            else:
                break

        else:
            print('暂未保存信息')
            return


def sort():
    show()
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student_list = rfile.readlines()
            student_new = []
            for item in student_list:
                d = dict(eval(item))
                student_new.append(d)
    else:
        return
    #reverse选择
    asc_or_desc = input('请选择（0升序，1降序）：')
    if asc_or_desc == '0':
        asc_or_desc_bool = False
    elif asc_or_desc == '1':
        asc_or_desc_bool = True
    else:
        print('输入有误，重新输入！')
        sort()
    #排序选择
    mode = input('请选择排序方式（1.按英语成绩排序；2.按python成绩排序；3.按java成绩排序；0.按总成绩排序）：')
    if mode == '1':
        student_new.sort(key=lambda x: int(x['english']), reverse=asc_or_desc_bool)
    elif mode == '2':
        student_new.sort(key=lambda x: int(x['python']), reverse=asc_or_desc_bool)
    elif mode == '3':
        student_new.sort(key=lambda x: int(x['java']), reverse=asc_or_desc_bool)
    elif mode == '0':
        student_new.sort(key=lambda x: int(x['java']) + int(x['python']) + int(x['java']), reverse=asc_or_desc_bool)
    else:
        print('输入有误，重新输入！')
        sort()
    show_student(student_new)  # 显示排序结果


def total():
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            student = rfile.readlines()
            if student:
                print('共有{}人。'.format(len(student)))
            else:
                print('无录入信息！')
    else:
        print('暂未保存信息！')


def show_student(lst):
    if len(lst) == 0:
        print('没有信息，无数据！')
        return
    # 定义标题显示格式
    format_title = '{:^6}\t{:^11}\t{:^6}\t{:^8}\t{:^8}\t{:^8}'
    print(format_title.format('ID', '姓 名', '英语成绩', 'python成绩', 'java成绩', '总成绩'))
    # 定义内容显示格式
    format_data = '{:^6}\t{:^12}\t{:^8}\t{:^10}\t{:^10}\t{:^8}'
    for item in lst:
        print(format_data.format(item.get('id'),
                                 item.get('name'),
                                 item.get('english'),
                                 item.get('python'),
                                 item.get('java'),
                                 int(item.get('english')) + int(item.get('python')) + int(item.get('java'))
                                 ))


def show():
    student_list = []
    if os.path.exists(filename):
        with open(filename, 'r', encoding='utf-8') as rfile:
            students = rfile.readlines()
        for item in students:
            student_list.append(eval(item))
        if student_list:
            show_student(student_list)
    else:
        print('暂未保存数据信息！')


def menu():
    print('=======================信息管理系统=======================')
    print('------------------------- 主菜单 ------------------------')
    print('\t\t\t\t\t  1.输入信息')
    print('\t\t\t\t\t  2.删除信息')
    print('\t\t\t\t\t  3.修改信息')
    print('\t\t\t\t\t  4.查找信息')
    print('\t\t\t\t\t  5.信息排序')
    print('\t\t\t\t\t  6.统计信息')
    print('\t\t\t\t\t  7.显示所有信息')
    print('\t\t\t\t\t  0.退出系统')
    print('=========================================================')
